package com.dwxt.cms.service;

import com.dwxt.cms.dao.AdminUserMapper;
import com.dwxt.cms.entity.*;
import com.dwxt.cms.entity.dto.AdminUserDTO;
import com.dwxt.cms.entity.vo.AdminUserVO;
import com.dwxt.cms.entity.vo.MenuVO;
import com.dwxt.cms.service.feign.TrainHallService;
import com.dwxt.common.base.AdminUserType;
import com.dwxt.common.base.BaseResult;
import com.dwxt.common.base.StatusCode;
import com.dwxt.common.base.YesOrNo;
import com.dwxt.common.util.JsonUtils;
import com.dwxt.common.util.MD5Utils;
import com.dwxt.common.util.PartyUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class UserServiceAdmin {
    @Autowired
    private AdminUserMapper adminUserMapper;

    @Autowired
    private UserRoleServiceAdmin userRoleServiceAdmin;

    @Autowired
    private MenuServiceAdmin menuServiceAdmin;

    @Autowired
    private PermissionServiceAdmin permissionServiceAdmin;

    @Autowired
    private TrainHallService trainHallService;


    /**
     * 根据名字查找用户
     *
     * @param phone
     * @return AdminUser
     */
    public AdminUser selectByPhone(String phone) {
        AdminUserExample example = new AdminUserExample();
        example.createCriteria().andPhoneEqualTo(phone);
        List<AdminUser> adminUsers = adminUserMapper.selectByExample(example);
        return adminUsers.isEmpty() ? null : adminUsers.get(0);
    }

    /**
     * 校验用户名和密码
     *
     * @param phone
     * @param password
     * @return
     */
    public AdminUser login(String phone, String password, String type) {
        AdminUser user = selectByPhone(phone);
        if (user != null && MD5Utils.MD5Encode(password).equalsIgnoreCase(user.getPassword()) && user.getIsOn() == YesOrNo.YES) {
            if (user.getType().contains(AdminUserType.ADMIN) || user.getType().contains(type)) {
                return user;
            }
        }
        return null;
    }

    /**
     * @param adminUserDTO
     * @return
     */
    @Transactional
    public BaseResult createOrUpdateUser(AdminUserDTO adminUserDTO) {
        List<Integer> roleIds = adminUserDTO.getRoleIds();
        if (roleIds == null) {
            return BaseResult.build(StatusCode.ROLE_NOT_EXIST);
        }
        StringBuilder sb = new StringBuilder();
        for (Integer roleId : roleIds) {
            sb.append(roleId).append(",");
        }
        if (adminUserDTO.getId() == null) {
            AdminUser user = selectByPhone(adminUserDTO.getPhone());
            if (user == null) {
                user = new AdminUser();
                user.setPhone(adminUserDTO.getPhone());
                user.setUsername(adminUserDTO.getUsername());
                user.setPassword(MD5Utils.MD5Encode(adminUserDTO.getPassword().trim()));
                user.setType(sb.toString());
                user.setNote(adminUserDTO.getNote());
                int i = adminUserMapper.insertSelective(user);
                Integer userId = user.getId();
                //批量插入用户角色
                userRoleServiceAdmin.batchInsert(userId, roleIds);
                return BaseResult.ok(user);
            } else {
                return BaseResult.build(StatusCode.USERNAME_EXIST);
            }
        } else {
            if (StringUtils.isNotBlank(adminUserDTO.getPassword())) {
                adminUserDTO.setPassword(MD5Utils.MD5Encode(adminUserDTO.getPassword().trim()));
            }
            if (StringUtils.isNotBlank(adminUserDTO.getUsername())) {
                adminUserDTO.setUsername(adminUserDTO.getUsername().trim());
            }
            try {
                adminUserDTO.setType(sb.toString());
                adminUserMapper.updateByPrimaryKeySelective(adminUserDTO);
            } catch (org.springframework.dao.DuplicateKeyException e) {
                return BaseResult.build(StatusCode.USERNAME_EXIST);
            }
            if (roleIds != null && roleIds.size() != 0) {
                //修改用户的角色
                userRoleServiceAdmin.deleteByUserId(adminUserDTO.getId());
                userRoleServiceAdmin.batchInsert(adminUserDTO.getId(), roleIds);
            }
            return BaseResult.ok();
        }
    }

    public List<AdminUserVO> selectAllUserVo() {
        return adminUserMapper.selectAllUserVo();
    }


    @Transactional
    public int batchDeleteById(Integer[] id) {
        AdminUserExample example = new AdminUserExample();
        example.createCriteria().andIdIn(Arrays.asList(id));
        int i = adminUserMapper.deleteByExample(example);

        //批量删除用户角色记录
        userRoleServiceAdmin.deleteByUserIds(id);

        //培训馆删除
        trainHallService.delete(id);
        return i;
    }

    public List<MenuVO> menuList(Integer id, Integer type) {
        List<UserRole> userRoles = userRoleServiceAdmin.selectByUserId(id);
        List<Integer> roleIds = userRoles.stream().map(UserRole::getRoleId).collect(Collectors.toList());
        return menuServiceAdmin.selectMenuVOByRoleIds(roleIds, type);
    }

    public List<AdminUser> selectAllMallUser(Integer type) {
        AdminUserExample example = new AdminUserExample();
        example.createCriteria().andTypeLike("%" + AdminUserType.MALL + "%");
        List<AdminUser> adminUserList = adminUserMapper.selectByExample(example);
        if (type == 0) {
            return adminUserList;
        } else {
            List<AdminUser> userListType = new ArrayList<>();
            for (AdminUser adminUser : adminUserList) {
                BaseResult baseResult = trainHallService.selectHallByKey(adminUser.getId());
                if (type == 6) {
                    if (baseResult.getData() != null) {
                        userListType.add(adminUser);
                    }
                } else {
                    if (baseResult.getData() == null) {
                        userListType.add(adminUser);
                    }
                }
            }
            return userListType;
        }
    }

    public AdminUser selectUser() {
        return adminUserMapper.selectByPrimaryKey(Integer.parseInt(PartyUtil.getCurrentUserId()));
    }

    public List<AdminUser> selectMallUserPage(AdminUser adminUser) {

        AdminUserExample example = new AdminUserExample();
        example.setOrderByClause("create_time desc");
        AdminUserExample.Criteria criteria = example.createCriteria();
        criteria.andTypeLike("%" + AdminUserType.MALL + "%");
        if (StringUtils.isNotBlank(adminUser.getUsername())) {
            criteria.andUsernameLike(adminUser.getUsername() + "%");
        }
        if (StringUtils.isNotBlank(adminUser.getPhone())) {
            criteria.andPhoneEqualTo(adminUser.getPhone());
        }
        return adminUserMapper.selectByExample(example);
    }


    public BaseResult selectUserHallByKey(Integer id) {
        AdminUser adminUser = adminUserMapper.selectByPrimaryKey(id);
        BaseResult baseResult = trainHallService.selectHallByKey(id);
        if (baseResult.getData() != null) {
            HashMap hall = JsonUtils.jsonToPojo(JsonUtils.objectToJson(baseResult.getData()), HashMap.class);
            HashMap adminUserMap = JsonUtils.jsonToPojo(JsonUtils.objectToJson(adminUser), HashMap.class);
            adminUserMap.putAll(hall);
            adminUserMap.put("type", "6");
            return BaseResult.ok(adminUserMap);
        } else {
            adminUser.setType("1");
            return BaseResult.ok(adminUser);
        }

    }

    public List<Role> selectRolesByUserId(String userId) {
        return adminUserMapper.selectRolesByUserId(userId);
    }

    public List<String> getPermissionUrl(Integer id) {
        List<UserRole> userRoles = userRoleServiceAdmin.selectByUserId(id);
        List<Integer> roleIds = userRoles.stream().map(UserRole::getRoleId).collect(Collectors.toList());
        List<Permission> permissions = permissionServiceAdmin.selectByRoleList(roleIds);
        List<String> permissionUrls = permissions.stream().map(Permission::getUrl).collect(Collectors.toList());
        return permissionUrls;
    }

    public void disOrEnable(Integer id) {
        AdminUser adminUser = adminUserMapper.selectByPrimaryKey(id);
        if (adminUser.getIsOn() == YesOrNo.YES) {
            adminUser.setIsOn(YesOrNo.NO);
        } else {
            adminUser.setIsOn(YesOrNo.YES);
        }
        adminUserMapper.updateByPrimaryKeySelective(adminUser);
    }

    public AdminUser selectUserById(Integer id) {
        return adminUserMapper.selectByPrimaryKey(id);
    }

    public List<AdminUser> selectAllAdminUser() {
        AdminUserExample example = new AdminUserExample();
        example.createCriteria().andTypeLike("%" + AdminUserType.ADMIN + "%");
        return adminUserMapper.selectByExample(example);
    }
}
